package com.java2nb.novel.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 通知幂等性工具（基于Redis）
 */
@Component
public class NotifyIdempotentUtils {
    private static final String PAY_NOTIFY_KEY_PREFIX = "pay:notify:pay_order:"; // 支付通知状态Key前缀
    private static final String REFUND_NOTIFY_KEY_PREFIX = "pay:notify:refund_order:"; // 退款通知状态Key前缀
    private static final long NOTIFY_EXPIRE_DAYS = 7; // 通知状态保留7天

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 校验支付通知是否已处理（幂等性）
     * @param payOrderId 支付订单号
     * @return true=已处理，false=未处理
     */
    public boolean checkPayNotifyProcessed(String payOrderId) {
        String key = PAY_NOTIFY_KEY_PREFIX + payOrderId;
        return redisTemplate.hasKey(key);
    }

    /**
     * 标记支付通知已处理
     * @param payOrderId 支付订单号
     */
    public void markPayNotifyProcessed(String payOrderId) {
        String key = PAY_NOTIFY_KEY_PREFIX + payOrderId;
        redisTemplate.opsForValue().set(key, "1", NOTIFY_EXPIRE_DAYS, TimeUnit.DAYS);
    }

    /**
     * 校验退款通知是否已处理（幂等性）
     * @param refundOrderId 退款订单号
     * @return true=已处理，false=未处理
     */
    public boolean checkRefundNotifyProcessed(String refundOrderId) {
        String key = REFUND_NOTIFY_KEY_PREFIX + refundOrderId;
        return redisTemplate.hasKey(key);
    }

    /**
     * 标记退款通知已处理
     * @param refundOrderId 退款订单号
     */
    public void markRefundNotifyProcessed(String refundOrderId) {
        String key = REFUND_NOTIFY_KEY_PREFIX + refundOrderId;
        redisTemplate.opsForValue().set(key, "1", NOTIFY_EXPIRE_DAYS, TimeUnit.DAYS);
    }
}